package edu.gyc.testthread;

import java.util.ArrayList;
import java.util.List;

class Worker implements Runnable{
    List<Integer> taskList;
    List<Long> resultList;
    long sum=0;
    int n;
    public Worker(List<Integer> taskList,List<Long> resultList,int n) {
        this.taskList = taskList;
        this.resultList=resultList;
        this.n=n;
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"开始计算...");
        for (int i : taskList) {
            sum+=i;
        }
        synchronized (resultList) {
            resultList.add(n,sum);
            System.out.println(n+":"+sum);
        }
    }

}
public class Test {
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n;  //(先计算出余数)
        int number = source.size() / n;  //然后是商
        int offset = 0;//偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }
    public static void main(String[] args) {
        Long start=System.currentTimeMillis();
        int n=5;
        ArrayList<Integer> data = new ArrayList<>();
        for (int i = 1; i <=100000000; i++) {
            data.add(i);
        }
        List<List<Integer>> taskList = averageAssign(data, n);
        List<Long> resultList = new ArrayList<>();
        for(int i=0;i<n;i++){
            resultList.add(0L);
        }
        for (int i=0;i<n;i++) {

            Thread thread=  new Thread(new Worker(taskList.get(i),resultList,i));
            thread.start();
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        long result=0L;
        for (Long i : resultList) {
            result+=i;
        }
        System.out.println("sum="+result+" expire: "+(System.currentTimeMillis()-start)+"ms.");
    }
}
